package com.yh.crystal.chinaunionPay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils {

	public String httpPostWithJSON(String url, String encoderJson) throws Exception {
		// 将JSON进行UTF-8编码,以便传输中文
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		StringEntity se = new StringEntity(encoderJson, "UTF8");
		httpPost.setEntity(se);
		CloseableHttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		InputStream content = entity.getContent();

		net.sf.json.JSONObject json = toJson(content);

		return json.toString();
	}

	public String httpGet(String url) throws Exception {
		// 将JSON进行UTF-8编码,以便传输中文
		DefaultHttpClient httpClient = new DefaultHttpClient();

		HttpGet httpGet = new HttpGet(url);

		CloseableHttpResponse response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		InputStream content = entity.getContent();

		net.sf.json.JSONObject json = toJson(content);

		return json.toString();
	}

	public static net.sf.json.JSONObject toJson(InputStream in) throws UnsupportedEncodingException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8"));
		StringBuilder sb = new StringBuilder();
		String line;

		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String string = sb.toString();

		if (string != null && !string.equals("")) {
			return net.sf.json.JSONObject.fromObject(string);
		} else {
			return new net.sf.json.JSONObject();
		}
	}

}
